package com.neuedu.jdbc;

import com.neuedu.jdbc.v3.entity.Dept;
import com.neuedu.jdbc.v3.entity.Emp;
import org.junit.Test;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Reflection {



    @Test
    public void test() throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class deptClazz = Dept.class;
        Class empClazz = Emp.class;
        //实例化对象
        Object obj1 = deptClazz.newInstance();
        Object obj2 = empClazz.newInstance();
        System.out.println(obj1);
        System.out.println(obj2);

        //Dept.class; ---> obj1
//        obj1  .setDeptNo
        //反射的机制, 通过Classs获取到对象 的属性  方法
        // deptno  set --->   setDeptno
        Method setDeptno = deptClazz.getDeclaredMethod("setDeptno", Integer.class);
        Method setDname = deptClazz.getDeclaredMethod("setDname", String.class);

        //obj1.setDepto(100);  setDeptNo setDeptno
        setDeptno.invoke(obj1,100);
        setDname.invoke(obj1,"开发");
        System.out.println(obj1);
    }

    @Test
    public void testInvoke() throws InstantiationException, IllegalAccessException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException {
        Class deptClazz = Dept.class;


        Object obj1 = deptClazz.newInstance();
        System.out.println("obj1 = " + obj1);


//        String columnName = "deptno";
        String columnName = "dname";
        Object value = "abc";
//        String functionName = "setDeptno";
        String functionName = "set"+columnName.substring(0,1).toUpperCase()+columnName.substring(1);
        System.out.println("functionName = " + functionName);


        //获取字段对应的属性
        Field declaredField = deptClazz.getDeclaredField(columnName);
        Class<?> fieldType = declaredField.getType();

        Method method = deptClazz.getDeclaredMethod(functionName, fieldType);

        method.invoke(obj1,value);

        System.out.println("obj1 = " + obj1);


    }






}
